<?php

namespace App\Http\Controllers\Touch\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\HomeController;

use Auth;
use Storage;
use App\Models\UserInfo;

class IndexController extends HomeController
{
	/**
	 * 获取当前登录用户基本信息、只有头像和昵称
	 * @return [type] [description]
	 */
    public function baseInfo(){
        $user = Auth::user()->toArray();
        $user['headimgurl'] =  $user['headimgurl']!='' ?  asset('/upload/'.$user['headimgurl']) : '';
    	$this->ajaxJson(0,'',$user);
    }

    /**
     * 获取当前用户所有信息
     * @return [type] [description]
     */
    public function info(){
    	$user = Auth::user();
        $data['id'] = $user->id;
        $data['account'] = $user->phone;
        $data['nickname'] = $user->nickname;
        $userInfo = UserInfo::find($user->id);
        if($userInfo){
            $data['sex'] = $userInfo->sex;
            $data['birthday'] = $userInfo->birthday;
        }
        $data['headimgurl'] =  $user['headimgurl']!='' ?  asset('/upload/'.$user['headimgurl']) : '';
        $this->ajaxJson(0,'',$data);
    }

    /**
     * 用户信息保存
     * @return [type] [description]
     */
    public function infoSave(Request $request){
        //保存基本信息
        $user = Auth::user();
        $user->nickname = $request->input('nickname');
        $filePath = 'avatar/'.date('Y',time()).'/'.date('m',time()).'/'.date('d',time())."/".date('H',time()).'/';
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $request->input('headimgurl'), $result)){
            $type = $result[2];
            $new_file = date('YmdHis').str_random(15).".{$type}";
            if(!Storage::put($filePath.$new_file, base64_decode(str_replace($result[1], '', $request->input('headimgurl'))))){
                exit(json_encode(array('code'=>1,'msg'=>'上传图片失败,请重试!')));
            }
            $user->headimgurl = $filePath.$new_file;
        }
        $user->save();

        //用户其他信息保存
        $userInfo = UserInfo::find($user->id);
        if(!$userInfo){
            $userInfo = new UserInfo();
            $userInfo->id = $user->id;
        }
        $userInfo->sex = $request->input('sex');
        $userInfo->birthday = $request->input('birthday');
        $userInfo->save();
        $this->ajaxJson(0,'保存成功',['headimgurl' => '/upload/'.$user->headimgurl ]);
    }
}
